package com.ajou.adonate.imap;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;

import javax.mail.*;
import javax.mail.Flags.Flag;
import javax.mail.search.SearchTerm;

import com.ajou.adonate.filemgr.*;
import com.ajou.adonate.database.*;

import Threadpool.ThreadPool;

import com.mysql.jdbc.Driver;

public class MailReader extends Thread{
	private UserSession m_UserSession = null;
	private HashMap<String, MailContext> m_FileList = new HashMap<String, MailContext>();
	private MailContext m_DownThread;
	
	public MailReader(UserSession TempSession) {
		m_UserSession = TempSession;
	}
	
	public HashMap<String, MailContext>  getFileList() {
		return m_FileList;
	}
	
	// mail context parser	
	public MailContext MailParser(String subject) {
		MailContext reContext = new MailContext();
		String [] Context  = subject.split("]", 10);
		
		// file name
		int flag = Context[1].indexOf(":");
		Context[1] = Context[1].substring(flag+1);	
		
		// file id
		flag = Context[2].indexOf(":");
		Context[2] = Context[2].substring(flag+1);
		
		// file index
		flag = Context[3].indexOf(":");
		Context[3] = Context[3].substring(flag+1);
		
		// file size
		flag = Context[4].indexOf(":");
		Context[4] = Context[4].substring(flag+1);
		
		// file Directory Id
		flag = Context[5].indexOf(":");
		Context[5] = Context[5].substring(flag+1);
		
		//Context[5] = Context[5].substring(0, Context[5].length()-1);
		
		reContext.setFileName(Context[1]);
		reContext.setFileHashId(Integer.valueOf(Context[2]).intValue());
		reContext.setIndexNum(Integer.valueOf(Context[3]).intValue());
		reContext.setFileSize(Integer.valueOf(Context[4]).intValue());
		reContext.setDirectoryId(Integer.valueOf(Context[5]).intValue());
		//System.out.println(" >> " + reContext.toString());
		return reContext;
	}
	
	public MailContext getUnreadMailContext(String FileName) {
		MailContext reContext = null;
		
		try {
			Folder mdFolder =  m_UserSession.getFolder();
			mdFolder.open(Folder.READ_WRITE);
			
			int TotalCount = mdFolder.getMessageCount();
			int UnreadMsgCount  =  mdFolder.getUnreadMessageCount();
			int index =0;
			
			// get Unread Message= new upload file
			for(index = 0; index < UnreadMsgCount; ++index ) {
				Message Msg = mdFolder.getMessage(TotalCount-index);
				String StrSub = Msg.getSubject();
				
				if(StrSub.contains(FileName) == true) {
					Msg.setFlag(Flag.SEEN, true);

					if(reContext != null) {
						MailContext newMsg = MailParser(StrSub);;
						reContext.AddMailContext(newMsg, Msg.getMessageNumber());
					} else {
						reContext = MailParser(StrSub);
						reContext.AddMailNum(reContext.getIndexNum(), Msg.getMessageNumber());
					}
				}
			}
			mdFolder.close(false);
		}  catch (NoSuchProviderException e) {
            e.printStackTrace();
            System.exit(1);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		//System.out.println("   NEW >> " +  reContext.toString());
		return reContext;
	}
	
	public void RestFileList() {
		//Store AllMsg = m_UserSession.getStore();
		try {
	        if(m_UserSession.getStore().isConnected() == true) {
	        	Folder inbox = m_UserSession.getFolder();
	            inbox.open(Folder.READ_ONLY);
	            Message messages[] = inbox.getMessages();
	            
	            if(!m_FileList.isEmpty()) m_FileList.clear();
	            
	            for(Message message:messages) {
	            	if(message.getSubject().indexOf("[ADonate]") == 0) {
	            		String StrSub = message.getSubject();
	            		String FileDes = message.getDescription();
	            		
	            		// create MailContext from mail subject
	            		MailContext newContext =   MailParser(StrSub);
	            		
	            		if(m_FileList.containsKey(newContext.getFileName()) == true ) {
	            			// exist
	            			MailContext preMailContext = m_FileList.get(newContext.getFileName());
	            			preMailContext.AddMailContext(newContext, message.getMessageNumber());
	            			
	            			System.out.println("ToString>> " + preMailContext.toString());
	            		} else {
	            			// not exist
	            			newContext.setFileDescription(FileDes);
	            			newContext.AddMailNum(newContext.getIndexNum(), message.getMessageNumber());
	            			m_FileList.put(newContext.getFileName(), newContext);
	            			
	            			System.out.println("ToString>> " + newContext.toString());
	            		}
	            	}
	            }
	            inbox.close(true);
	        }
       } catch (NoSuchProviderException e) {
            e.printStackTrace();
            System.exit(1);
       } catch (MessagingException e) {
    	   System.out.println("LOGIN invalid user or password");
       }
	}
	
//	public void SyncDBWithMail(int Member_Id)
//	{
//		//delete database
//		DatabaseManager DBConnect = new DatabaseManager();
//		DBConnect.refreshFileList(Member_Id);
//		Iterator<String> iter =  m_FileList.keySet().iterator();
//		
//		while(iter.hasNext()) {
//			DBConnect.uploadFile(Member_Id,  m_FileList.get(iter.next()) );
//		}
//	}

	public Boolean FileDownload(String FileName) {
		MailContext DownFile = null;
		if(m_FileList.isEmpty() == false) {
			// start thread
			DownFile = m_FileList.get(FileName);
			if(DownFile != null && DownFile.getMailNumList().size() > 0) {
				System.out.println(DownFile.getFileName()+" --> start()");
				m_DownThread = DownFile;
				//start();
			}
		}
		return false;
	}

	public void run() {
		try {
			if(m_UserSession.getStore().isConnected() == true) {
				Folder inbox = m_UserSession.getFolder();
	            inbox.open(Folder.READ_ONLY);
	            HashMap<String,String> filePathList = new HashMap<String,String>();
	            
				int MaxIndex = m_DownThread.getMailCount();
				HashMap<String, Integer> MailList = m_DownThread.getMailNumList();	
				ThreadPool pool = new ThreadPool(MaxIndex);
				
				System.out.println("Download Start!!( Thread : "+MaxIndex +")");
				for(int i =0; i < MaxIndex; ++i) {
					Integer MailId =  MailList.get(Integer.toString(i));
					Message msg =  inbox.getMessage(MailId.intValue());
					
					FileDownloader Downloader = new FileDownloader();
					String filePath = Downloader.DownloadFile(msg); 
					pool.runTask(Downloader);
					
					filePath = "D:\\upload\\DownTemp\\" + filePath;
					filePathList.put(Integer.valueOf(i).toString(), filePath);
				}
				pool.join();
				System.out.println("Complate Download File : " + MaxIndex );
				
				FileMerge Fm = new FileMerge(filePathList);
				Fm.mergeFileList("D:\\upload\\", m_DownThread.getFileName()+"."+m_DownThread.getFileFormat());
				System.out.println("Complate Merge File : " + MaxIndex );
				
				for(int i=0; i<filePathList.size(); ++i) {
					File delFile = new File(filePathList.get( Integer.valueOf(i).toString() ));
					delFile.delete();
				}
				pool.close();
				
	        }
		} catch (Exception e) {
			// TODO: handle exception
		}
	}	
}